import { defineStore } from "pinia";
import {ref} from 'vue'
import {userLogin,getUserInfoByToken} from '@/apis/user'
import { transListToTreeData } from "@/utils";
import { useRouterConfig } from "@/testAddRoute";
import router from "@/router";
import Layout from "@/views/Layout/index.vue";

const useRoute = useRouterConfig()

export const useUserStore = defineStore('user',()=>{
  const userTokenInfo = ref({})
  const userInfo = ref({})
  const userMenuPermissions = ref([])

  /**
   * 登录存储用户信息
   * @param {*} data 参数
   */
  const getUserInfo = async(data)=>{
    const res  = await userLogin(data)
    const user= await getUserInfoByToken(res.token)
    const filtered = user.permissions.filter((i) => i.isButton == false);
    const makedMenus = useRoute.makeMenuRoute(filtered)
    const treeMenu = transListToTreeData(makedMenus, 0);
    const permissionsTree = transListToTreeData(user.permissions,0)
    userMenuPermissions.value = permissionsTree
    const rr = {
      path:'/',
      component:Layout,
      redirect:'/home',
      children:treeMenu
    }
    router.addRoute(rr)
    localStorage.setItem('menuList',JSON.stringify(treeMenu))
    // localStorage.setItem('permissionsTree',JSON.stringify(permissionsTree))
    userTokenInfo.value = res
    userInfo.value = user
  }

  /**
   * 退出清空用户信息
   */
  const clearUserInfo=()=>{
    userTokenInfo.value={}
    userInfo.value={}
    localStorage.clear('menuList')
  }


  return { userTokenInfo,userInfo,userMenuPermissions,getUserInfo,clearUserInfo}
},{
  persist:true
})